package com.example.UI;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;

import com.example.UI.database.CourseMessage;
import com.example.UI.entity.Course;
import com.example.ui.R;


public class SelectCourseActivity extends AppCompatActivity {

    private EditText editTextCourseName;
    private EditText editTextCourseNumber;
    private EditText editTextCourseTime;
    private EditText editTextCourseTeacher;
    private EditText editTextcourseClass;
    private Button buttonSelectCourse;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_select_course);

        editTextCourseName = findViewById(R.id.editTextCourseName);
        editTextCourseNumber = findViewById(R.id.editTextCourseNumber);
        editTextCourseTime = findViewById(R.id.editTextCourseTime);
        editTextCourseTeacher = findViewById(R.id.editTextCourseTeacher);
        editTextcourseClass = findViewById(R.id.editTextcourseClass);
        buttonSelectCourse = findViewById(R.id.buttonSelectCourse);

        buttonSelectCourse.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectCourse();
            }
        });
    }


    private void selectCourse() {
        // 从输入字段获取选课信息
        String courseName = editTextCourseName.getText().toString().trim();
        String courseNumber = editTextCourseNumber.getText().toString().trim();
        String courseTeacher = editTextCourseTeacher.getText().toString().trim();
        String courseClass = editTextcourseClass.getText().toString().trim();
        String courseTimeStr = editTextCourseTime.getText().toString().trim();

        // 输入验证
        if (courseName.isEmpty() || courseNumber.isEmpty() || courseTeacher.isEmpty() || courseClass.isEmpty() || courseTimeStr.isEmpty()) {
            Toast.makeText(this, "所有字段都不能为空", Toast.LENGTH_SHORT).show();
            return;
        }

        Course course;
        try {
            int courseTime = Integer.parseInt(courseTimeStr);
            // 创建Course对象
            course = new Course(courseName, courseNumber, courseTeacher, courseClass, courseTime);
        } catch (NumberFormatException e) {
            Toast.makeText(this, "课程时间必须是有效的整数", Toast.LENGTH_SHORT).show();
            return;
        }

        // 实例化CourseMessage并添加课程
        CourseMessage courseMessage = new CourseMessage(this);
        long newRowId = courseMessage.addCourse(course);

        if (newRowId != -1) {
            // 添加成功
            Toast.makeText(this, "选课成功，课程ID: " + newRowId, Toast.LENGTH_SHORT).show();
            // 可以在这里添加逻辑，如清空输入框或者跳转到其他Activity
        } else {
            // 添加失败
            Toast.makeText(this, "选课失败，请重试", Toast.LENGTH_SHORT).show();
        }
    }
}